#consoleLogic.py - All of the logic unique to the console program

from fileSelection import *
import getpass
import time

class consoleLogic(object):
    """Menu logic for console program."""

    def __init__(self):
        """Initializes."""
        pass

    def clear(self):
        """Clears console screen.
        
        Works on multiple platforms.
        """
        os.system('cls' if os.name == 'nt' else 'clear')

    def selectFiles(self,fileNames,fileTypes,directory=os.curdir):
        """Presents menus to select files.
        
        fileNames should be a description of
        the file for the user.
        fileNames and fileTypes should be
        given as arrays.
        """
        self.myFolder=fileSelection(directory)
        self.selectedFiles=[]
        for index,name in enumerate(fileNames):
            if len(self.myFolder.createListByType(fileTypes[index]))==1:
                print 'The program has automatically selected ' + self.myFolder.createListByType(fileTypes[index])[0]
                self.selectedFiles.append(self.myFolder.createListByType(fileTypes[index])[0])
            else:
                print 'Please select the ' + name + ' from the following list'
                for counter,fileName in enumerate(self.myFolder.createListByType(fileTypes[index])):
                    print str(counter+1) + ') ' + fileName
                self.selection=raw_input('Which file do you want to choose? ')
                self.selectedFiles.append(self.myFolder.createListByType(fileTypes[index])[int(self.selection)-1])

    def getPassword(self):
        """Prompts for password."""
        self.password=getpass.getpass("Enter your gmail password: ")
        return self.password

    def getNumOfQuestions(self):
        """Prompts for number of questions."""
        self.numOfQuestions=int(raw_input("Enter the number of questions in the quiz: "))
        return self.numOfQuestions

    def getPoints(self,numOfQuestions):
        """Gets the necessary point values for grading."""
        self.pointsRightAnswer=int(raw_input("How many points do you want to award for a right answer?: "))
        self.pointsWrongAnswer=int(raw_input("How many points do you want to award for a wrong answer?: "))
        self.pointsNoAnswer=int(raw_input("How many points do you want to award for no answer?: "))
        self.extraCreditString=raw_input("Should all right answers be valued as exactly 100%? (y,n): ")
        self.extraCreditString=self.extraCreditString.lower()
        if self.extraCreditString=='y':
            self.totalPointsStr=str(int(self.pointsRightAnswer)*int(numOfQuestions))
        elif self.extraCreditString=='n':
            self.extraCreditStringTwo=raw_input("Should the entire quiz be extra credit? (y,n): ")
            self.extraCreditStringTwo=self.extraCreditStringTwo.lower()
            if self.extraCreditStringTwo=='y':
                self.totalPointsStr='ai'
            elif self.extraCreditStringTwo=='n':
                print 'Students can receive ' + str(int(self.pointsRightAnswer)*int(numOfQuestions)) + ' by answering every question correct.'
                self.totalPointsStr=raw_input("What point value should count as 100%: ")
            else:
                print 'Point value not set. Please restart program and answer y,n,Y, or N to the question just asked.'
        else:
            print 'Point value not set. Please restart program and answer y,n,Y, or N to the question just asked.'
    
    def displayTopResponses(self,sortedResponses,numToDisplay=4):
        """Displays top responses in console."""
        for qCount,question in enumerate(sortedResponses):
                print 'For question ' + str(qCount+1) + ' the top answers were:'
                for ansCount,answerPair in enumerate(question):
                        if ansCount<=(numToDisplay-1):
                                print 'The answer ' + answerPair[0] + ' was given by ' + str(answerPair[1]) + ' people'
                print ''

    def collectionLoop(self,responseObject,sleepTime=8):
        """Collects mail and keeps console screen updated."""
        try:
            while True:
                responseObject.collectionLoop()
                self.clear()
                print 'Press ctrl+c to stop quiz and show summary. A total of ' + str(len(responseObject.responses)) + ' people have responded'
                print 'The following people just responded: ',
                self.recentPeople=responseObject.peopleNew
                self.recentPeopleNum=[]
                for person in self.recentPeople:
                    self.recentPeopleNum.append(int(person))
                print str(sorted(self.recentPeopleNum)).strip('[]')
                self.allPeopleNum=[]
                print 'The following people have responded: ',
                for person in responseObject.responses:
                    self.allPeopleNum.append(int(person))
                print str(sorted(self.allPeopleNum)).strip('[]')
                time.sleep(12)
        except KeyboardInterrupt:
            self.clear()

    def hold(self,string='Press enter to quit'):
        """Keeps console up by displaying an input."""
        raw_input(string)

    def getAnswers(self,numOfQuestions):
        """Gets answers for each problem."""
        self.answers=[]
        for question in range(numOfQuestions):
            self.answer=str(raw_input('What is the answer to question ' + str(question+1) + '? '))
            self.answers.append(self.answer)
        return self.answers
